import Vue from 'vue'
import axios from 'axios'
import user from '../utils/user' 
import iView from 'iview' 
import Cookies from 'js-cookie'
import VueLocalStorage  from 'vue-localstorage'

//设置baseURI

axios.defaults.baseURL = '/api/v1';
axios.defaults.headers.common['Authorization'] = 'Bearer '+ user.getToken();

//axios request //默认传参
axios.interceptors.response.use(
  (config) => {
    if(config.method === 'post'){
      config.params = {  
            ...config.params
      }
    }  
    //登陆过期
    if(!config.data.ok && config.data.msg === 'Token is expired'){
        iView.Message.error("登录过期,请重新登陆！");
        setTimeout(() => {
          user.redirect();
        }, 3000) 
    }
    return config;
  } ,
  error => {
    let status = error.response.status; 
    //验证过期,跳转到登录地址
    if (status == 401) {
      localStorage.removeItem('token');
      Cookies.remove("lt_token");
      iView.Message.error(error.response.data.msg || "请重新登陆");
      setTimeout(() => {
        user.redirect();
      }, 3000)
    } else { 
      iView.Message.error('接口异常错误!');
    }
    return Promise.reject(error);
  }
); 

export default axios
